import wxValidate from 'wechat-validate'
Page({
  behaviors: [wxValidate],
  rules: {
    name: [
      { required: true, message: '访客姓名不能为空!' },
      { pattern: /[\u4e00-\u9fa5]{2,5}/, message: '访客姓名只能为中文!' },
    ],
    mobile: [
      { required: true, message: '访客手机号不能为空!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请填写正确的手机号码!' },
    ],
    houseId: [
      { required: true, message: '请选择到访的房屋!' }
    ],
    visitDate: [
      { required: true, message: '请选择到访的日期!' }
    ],
  },
  data: {
    dateLayerVisible: false,
    houseLayerVisible: false,
    houseList: [],
    gender: '',
    houseId: '',
    houseInfo: '',
    name: '',
    mobile: '',
    currentDate: Date.now(),
    maxDate: Date.now() + 1000 * 3600 * 24 * 3,
    visitDate: ''
  },
  onLoad() {
    this.getRoomList()
  },
  // 选择日期时执行
  selectDateInfo(ev) {
    console.log(ev);
    this.setData({
      visitDate: wx.utils.formatDate(ev.detail),
      dateLayerVisible: false,
    })
  },
  // 选择房屋时候执行
  selectHouseInfo(ev) {
    // console.log(ev);
    this.setData({
      houseId: ev.detail.id,
      houseInfo: ev.detail.name,
    })
  },
  // 获取房屋信息
  async getRoomList() {
    const res = await wx.http.get('/house')
    console.log(res);
    this.setData({
      houseList: res.data
    })
  },
  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  // 确认提交表单
  async goPassport() {
    if (!this.validate()) return
    const { name, gender, mobile, houseId, visitDate } = this.data
    const res = await wx.http.post('/visitor', { name, gender, mobile, houseId, visitDate })
    console.log(res);
    wx.reLaunch({
      url: '/visitor_pkg/pages/passport/index?id=' + res.data.id,
    })
  },
})
